package com.njsoft.huanxin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_chat.*
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.EMMessageListener


class ChatActivity : AppCompatActivity() {
   lateinit var adapter: MultiImageAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        initListener()
        init()
    }

    fun init() {
        adapter=MultiImageAdapter(this,null)
        ChatMsgList.layoutManager=LinearLayoutManager(this)
        ChatMsgList.adapter=adapter
    }

    fun initListener() {
        ChatMsg_Send.setOnClickListener {
            val mReceiverId = ChatMsg.text.toString().trim()
            val mChatMsgContent = ChatMsgContent.text.toString().trim()
            if (!TextUtils.isEmpty(mReceiverId) && !TextUtils.isEmpty(mChatMsgContent)) {
                val message = EMMessage.createTxtSendMessage(mChatMsgContent, mReceiverId)

//发送消息
                EMClient.getInstance().chatManager().sendMessage(message)
                adapter.addData(MsgBean(mChatMsgContent,MsgBean.MsgSend))
                ChatMsgList.scrollToPosition(adapter.itemCount-1)
            }
        }

        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    var msgListener: EMMessageListener = object : EMMessageListener {

        override fun onMessageReceived(messages: List<EMMessage>) {
            Log.v("---",messages.get(0).body.toString())
            //收到消息
            runOnUiThread {
                adapter.addData(MsgBean(messages.get(0).body.toString(),MsgBean.MsgReceicer))
                ChatMsgList.scrollToPosition(adapter.itemCount-1)
            }
        }

        override fun onCmdMessageReceived(messages: List<EMMessage>) {
            //收到透传消息
        }

        override fun onMessageRead(messages: List<EMMessage>) {
            //收到已读回执
        }

        override fun onMessageDelivered(message: List<EMMessage>) {
            //收到已送达回执
        }

        override fun onMessageRecalled(messages: List<EMMessage>) {
            //消息被撤回
        }

        override fun onMessageChanged(message: EMMessage, change: Any) {
            //消息状态变动
        }
    }

}
